<template>
  <div class="root">
    <!-- 工具条 -->
    <div class="toolbar">
      <el-button type="primary">保存并新增</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
    <el-row>
      <el-col :span="8">
        供应商：<el-input
          placeholder="请选择供应商"
          class="ipt"
          v-model="dataform.supplierName"
          @click="isshowsupplier = true"
        ></el-input>
      </el-col>
      <el-col :span="8">
        单据日期：
        <el-date-picker
          v-model="dataform.billDate"
          type="date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="请选择日期"
        />
      </el-col>
      <el-col :span="8"
        >单据编号：
        <span v-if="oldcode == undefined">GC。。。</span>
        <span v-else>{{ oldcode }}</span>
      </el-col>
    </el-row>
    <!-- 明细 -->
    <div style="margin-top: 10px; margin-bottom: 10px">
      <span>采购明细：</span>
      <el-button plain size="small" type="primary" @click="add">增行</el-button>
      <el-button plain size="small" type="primary" @click="derow"
        >删行</el-button
      >
    </div>
    <!-- 列表 -->
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @cell-dblclick="cellck"
        ref="purchaseRef"
        border
        header-algin="center"
        align="center"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="goodsname" label="商品" width="130">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.goodsname
            }}</span>
            <el-input
              v-else
              v-model="row.goodsname"
              placeholder="单击选择商品"
              @click="isshowgoods = true"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="100">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.unit
            }}</span>
            <el-input v-else v-model="row.unit"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="warehouse" label="仓库" width="100">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.warehouse
            }}</span>
            <el-input v-else v-model="row.warehouse"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量" width="140">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.num
            }}</span>
            <el-input-number
              v-else
              v-model="row.num"
              controls-position="right"
              :min="0"
              :step-strictly="true"
              :step="1"
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="采购单价" width="140">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.price
            }}</span>
            <el-input-number
              v-else
              v-model="row.price"
              controls-position="right"
              :precision="2"
              :min="0"
              :step="0.1"
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="rate" label="折扣率（%）" width="140">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.rate
            }}</span>
            <el-input-number
              v-else
              v-model="row.rate"
              controls-position="right"
              :precision="2"
              :min="0"
              :step="0.1"
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="rateMoney" label="折扣额" width="140">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.rateMoney
            }}</span>
            <el-input-number
              v-else
              v-model="row.rateMoney"
              controls-position="right"
              :precision="2"
              :min="0"
              :step="0.1"
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="采购金额" width="140">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.money
            }}</span>
            <el-input-number
              v-else
              v-model="row.money"
              controls-position="right"
              :precision="2"
              :min="0"
              :step="0.1"
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
              row.note
            }}</span>
            <el-input v-else v-model="row.note"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 订单备注明细 -->
    <div class="footer">
      <el-input
        placeholder="请填写订单备注信息"
        v-model="dataform.note"
        style="line-height: 30px"
      ></el-input>
    </div>
    <el-row style="margin-top: 20px">
      <el-col :span="6">
        优惠率&nbsp;&nbsp;&nbsp;
        <el-input-number
          class="ipt"
          :precision="2"
          :min="0"
          :step="1"
          v-model="dataform.rate"
        />%
      </el-col>
      <el-col :span="6">
        优惠金额
        <el-input-number
          class="ipt"
          :precision="2"
          :min="0"
          :step="1"
          v-model="dataform.rateMoney"
        />
      </el-col>
      <el-col :span="6">
        优惠后金额<el-input-number
          :precision="2"
          :min="0"
          :step="1"
          class="ipt"
          v-model="dataform.money"
        />
      </el-col>
      <el-col :span="6">
        本次付款<el-input-number
          :precision="2"
          :min="0"
          :step="1"
          class="ipt"
          v-model="dataform.pay"
        />
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px">
      <el-col :span="6">
        结算账户<el-input
          placeholder="请选择结算账户"
          class="ipt"
          v-model="dataform.supplierName"
        />
      </el-col>
      <el-col :span="6">
        本次欠款<el-input-number
          :precision="2"
          :min="0"
          :step="1"
          class="ipt"
          v-model="dataform.debt"
        />
      </el-col>
      <el-col :span="6">
        采购合同&nbsp;&nbsp;&nbsp;&nbsp;
        <!-- 文件上传 -->

        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          :action="host + '/api/upload'"
          multiple
          :on-success="uploadSuccess"
          :on-remove="handleRemove"
          :limit="3"
          :on-exceed="handleExceed"
        >
          <el-button type="primary"> 上传</el-button>
          <template #tip>
            <div class="el-upload__tip">上传jpg/jpeg类型的合同.</div>
          </template>
        </el-upload>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="look">查看合同</el-button>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px">
      <el-col :span="6">
        制单人&nbsp;&nbsp;&nbsp;&nbsp;<el-input
          class="ipt"
          v-model="dataform.prepared"
        />
      </el-col>
      <el-col :span="18"> </el-col>
    </el-row>
    <!-- 选择商品 -->
    <QueryGoods
      :visible="isshowgoods"
      @close="isshowgoods = false"
      @choose="choosegoods"
    ></QueryGoods>
    <!-- 选择供应商 -->
    <Supplier
      :visible="isshowsupplier"
      @close="isshowsupplier = false"
      @choose="choosesupplier"
    ></Supplier>
  </div>
</template>
<script setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  savePurchase,
  queryDetail,
  getPurchase
} from "@/api/platform/purchase.js";
import QueryGoods from "@/views/platform/purchase/queryGoods.vue";
import Supplier from "@/views/platform/purchase/supplier.vue";
import host from "@/utils/env.js";
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "purchase"
});
//列表唯一标识
const purchaseRef = ref(null);
//是否显示商品界面
const isshowgoods = ref(false);
//是否显示供应商界面
const isshowsupplier = ref(false);
//列表数据
const tableData = ref([]);
const dataform = ref({
  //采购单
  supplierId: 0,
  supplierName: "",
  billDate: "",
  contracts: [],
  note: "",
  rate: 0,
  rateMoney: 0,
  money: 0,
  pay: 0,
  accountId: 0,
  debt: 0,
  prepared: ""
});

const fileList = ref([]); //文件上传列表

//上传成功后的方法
function uploadSuccess(res, uploadFile) {
  if (res.code == 200) {
    //上传成功后 获取上传的路径及文件名称
    let tmp = {};
    tmp.path = res.data;
    tmp.filename = uploadFile.name;
    dataform.value.contracts.push(tmp);
  }
}

//文件移除的方法
function handleRemove(uploadFile) {
  //获取要删除的文件路径
  let path = uploadFile.response.data;
  //记录索引
  let index = -1;
  for (let i = 0, len = dataform.value.contracts.length; i < len; i++) {
    //临时对象
    let tmp = dataform.value.contracts[i];
    if (tmp.path == path) {
      index = i;
      break;
    }
  }

  //从列表中移除
  if (index != -1) {
    dataform.value.contracts.splice(index, 1);
  }
}

//文件超出限制的函数
function handleExceed(files, uploadFiles) {}

//保存
async function save() {
  let detail = []; //保存用户填写的明细
  //遍历表格数据
  tableData.value.forEach(r => {
    //判断当前对象中是否选择了商品 如果选择，则添加
    if (r.goodsname != undefined && r.goodsname != "") {
      detail.push(r);
    }
  });

  if (detail.length == 0) {
    ElMessage({
      message: "采购明细不能为空！",
      type: "warning"
    });
    return;
  }
  //采购单基本信息
  let data = dataform.value;
  //将明细加入到采购单
  data.purchaseDetailList = detail;
  //保存
  let res = await savePurchase(data);
  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
  }
}

function add() {
  addrow();
}

//删行
function derow() {
  let rows = purchaseRef.value.getSelectionRows(); //选中的行
  if (rows.length == 0) {
    ElMessage({
      message: "请选择行数据",
      type: "warning"
    });
  }

  //遍历要删除的行
  rows.forEach(r => {
    //删除
    removeData(r);
  });
}
//从tableData中移除行 r代表要删除的行
function removeData(r) {
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //获取当前行
    let tmp = tableData.value[i];
    //判断删除行
    if (tmp == r) {
      tableData.value.splice(i, 1);
      break;
    }
  }
}
//增加行数据
function addrow() {
  tableData.value.push({
    goodsid: "",
    goodsname: "",
    unit: "",
    warehouse: "",
    num: 0,
    price: 0,
    rate: 0,
    rateMoney: 0,
    money: 0,
    note: "",
    show: {}
  });
}
//初始函数
function init() {
  if (!dataform.value.id) {
    for (let i = 0; i < 10; i++) {
      addrow();
    }
  }
}

//记录上一次点击的行数据
const lastrow = ref({});

//修改行
function cellck(row, column) {
  cl();
  let tmp = column.property;
  //给对象增加动态属性
  row.show[tmp] = true;
  //记录点击行数据
  lastrow.value = row;
}

//清除输入框显示的标志属性
function cl() {
  if (lastrow.value.show != undefined) {
    //清空标志属性
    lastrow.value.show = {};
  }
}
//供应商选择
function choosesupplier(row) {
  dataform.value.supplierName = row.name;
  dataform.value.supplierId = row.id;
}

//商品选择
function choosegoods(data) {
  //双击选中的行
  let index = -1;
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    if (lastrow.value == tableData.value[i]) {
      index = i;
      break;
    }
  }
  for (let i = 0, len = data.length; i < len; i++) {
    //获取当前行
    let tmp = tableData.value[index];
    tmp.goodsname = data[i].name;
    tmp.price = data[i].price;
    tmp.warehouse = data[i].warehouseName;
    tmp.unit = data[i].unit;
    index++;
  }
  cl();
}

//记录金额
const allMoney = ref(0);

//监听采购单
watch(dataform, n => {
  // console.log(dataform.value)
  if (n.rate > 0) {
    //优惠金额
    n.rateMoney = allMoney.value * (n.rate / 100);
    //优惠后金额
    n.money = allMoney.value - n.rateMoney;
  };
  if(n.money>0 && n.pay>0){
    //本次欠款
    n.debt=n.money-m.pay;
  }


},
  {
    deep: true //深度遍历数组
  });

//监听函数 监听表格中每一行的数据
watch(
  tableData,
  n => {
    tableData.value.forEach(row => {
      if (row.num > 0 && row.price > 0) {
        //未优惠前金额
        let total = row.num * row.price;
        //计算折扣金额
        let tmpRatemoney = 0;
        if (row.rate > 0) {
          tmpRatemoney = total * (row.rate / 100);
          //更新当前行的折扣金额
          row.rateMoney = tmpRatemoney;
        }
        //计算采购金额
        row.money = total - tmpRatemoney;
        //计算全部金额
        // if(allMoney.value>0&&allMoney.value!=)
      }
    });
  },
  {
    deep: true //深度遍历数组
  }
);
//查看合同
function look() {
  console.log(allMoney.value);
}

//编码
const oldcode = ref("");
async function initdata() {
  if (dataform.value.id) {
    let res = await getPurchase(dataform.value.id);
    if (res.code == 200) {
      //接收合同列表
      let tmp = res.data.contracts;
      dataform.value.contracts = tmp;
      //展示文件上传列表
      tmp.forEach(t => {
        fileList.value.push({
          path: t.path,
          name: t.filename
        });
      });
      //接收商品列表
      res.data.purchaseDetailList.forEach(r => {
        tableData.value.push({
          goodsid: r.goodsId,
          goodsname: r.goodsname,
          unit: r.unit,
          warehouse: r.warehouse,
          num: r.num,
          price: r.price,
          rate: r.rate,
          rateMoney: r.rateMoney,
          money: r.money,
          note: r.note,
          show: {}
        });
      });
    }
  }
}
//生命周期函数
onMounted(() => {
  dataform.value.supplierName = history.state.supplierName;
  dataform.value.prepared = history.state.prepared;
  dataform.value.id = history.state.id;
  dataform.value.billDate = history.state.billDate;
  dataform.value.money = history.state.money;
  dataform.value.pay = history.state.pay;
  dataform.value.rateMoney = history.state.rateMoney;
  oldcode.value = history.state.CODE;
  initdata();
  init();
});
</script>
<style scoped>
.root {
  border: #ebeef5 1px solid;
  background-color: #fff;
  height: 100%;
  padding-left: 20px;
  padding-top: 20px;
}
.ipt {
  width: 200px;
  border-style: none;
  outline-style: none;
  border-bottom: #ebeef5 solid 1px;
}
.toolbar {
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 20px;
  padding-bottom: 20px;
}
.footer {
  margin-top: 20px;
}
</style>
